import 'question_model.dart';

// 考试状态枚举
enum ExamStatus {
  notStarted,   // 未开始
  inProgress,   // 进行中
  completed,    // 已完成
}

class Exam {
  final String id;
  final String title;
  final String description;
  final int duration; // 考试时长，以分钟为单位
  final List<Question> questions;
  final int totalScore; // 总分值
  final Map<String, String>? questionAnalysis; // 问题分析信息，key为题目ID，value为分析文本
  final List<String>? requirements; // 考试要求和规则
  final String? originalId; // 从试卷文件名中提取的原始试卷ID
  final int? sequence; // 试卷序号，用于区分同一试卷ID的不同版本

  Exam({
    required this.id,
    required this.title,
    required this.description,
    required this.duration,
    required this.questions,
    required this.totalScore,
    this.questionAnalysis,
    this.requirements,
    this.originalId,
    this.sequence,
  });

  // 获取某类型题目
  List<Question> getQuestionsByType(QuestionType type) {
    return questions.where((q) => q.type == type).toList();
  }

  // 序列化方法
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'duration': duration,
      'questions': questions.map((q) => q.toJson()).toList(),
      'totalScore': totalScore,
      'questionAnalysis': questionAnalysis,
      'requirements': requirements,
      'originalId': originalId,
      'sequence': sequence,
    };
  }

  // 从JSON反序列化
  factory Exam.fromJson(Map<String, dynamic> json) {
    // 解析题目列表
    List<Question> parsedQuestions = [];
    if (json['questions'] is List) {
      for (var questionJson in json['questions']) {
        if (questionJson is Map<String, dynamic>) {
          final question = Question.fromJson(questionJson);
          if (question != null) {
            parsedQuestions.add(question);
          }
        }
      }
    }

    return Exam(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      description: json['description'] ?? '',
      duration: json['duration'] ?? 60,
      questions: parsedQuestions,
      totalScore: json['totalScore'] ?? 0,
      questionAnalysis: json['questionAnalysis'] is Map
          ? Map<String, String>.from(json['questionAnalysis'])
          : null,
      requirements: json['requirements'] is List
          ? List<String>.from(json['requirements'])
          : null,
      originalId: json['originalId'],
      sequence: json['sequence'],
    );
  }
}

// 考试进行状态类，记录用户的考试进度
class ExamState {
  final String examId;
  final String userId;
  final String examTitle; // 考试标题
  final Map<String, dynamic> answers; // 已保存的答案
  final int remainingSeconds; // 剩余时间（秒）
  final DateTime lastUpdated; // 最后更新时间
  final ExamStatus status; // 考试状态
  final DateTime? lastActivity; // 最后活动时间，用于区分当前活动考试和需要恢复的考试

  ExamState({
    required this.examId,
    required this.userId,
    required this.examTitle,
    required this.answers,
    required this.remainingSeconds,
    required this.lastUpdated,
    required this.status,
    this.lastActivity,
  });

  // 创建一个新的考试状态（开始考试）
  factory ExamState.start(String examId, String userId, String examTitle, int durationInMinutes) {
    return ExamState(
      examId: examId,
      userId: userId,
      examTitle: examTitle,
      answers: {},
      remainingSeconds: durationInMinutes * 60,
      lastUpdated: DateTime.now(),
      status: ExamStatus.inProgress,
      lastActivity: DateTime.now(),
    );
  }

  // 更新考试状态（保存进度）
  ExamState updateProgress(Map<String, dynamic> newAnswers, int newRemainingSeconds, {DateTime? newLastActivity}) {
    return ExamState(
      examId: examId,
      userId: userId,
      examTitle: examTitle,
      answers: newAnswers,
      remainingSeconds: newRemainingSeconds,
      lastUpdated: DateTime.now(),
      status: ExamStatus.inProgress,
      lastActivity: newLastActivity ?? DateTime.now(),
    );
  }

  // 完成考试
  ExamState complete() {
    return ExamState(
      examId: examId,
      userId: userId,
      examTitle: examTitle,
      answers: answers,
      remainingSeconds: 0,
      lastUpdated: DateTime.now(),
      status: ExamStatus.completed,
      lastActivity: DateTime.now(),
    );
  }

  // 更新剩余时间
  ExamState updateRemainingTime(int newRemainingSeconds) {
    return ExamState(
      examId: examId,
      userId: userId,
      examTitle: examTitle,
      answers: answers,
      remainingSeconds: newRemainingSeconds,
      lastUpdated: DateTime.now(),
      status: ExamStatus.inProgress, // 确保状态为进行中，不是暂停
      lastActivity: lastActivity, // 保持原有的活动时间
    );
  }

  // 序列化方法
  Map<String, dynamic> toJson() {
    return {
      'examId': examId,
      'userId': userId,
      'examTitle': examTitle,
      'answers': answers,
      'remainingSeconds': remainingSeconds,
      'lastUpdated': lastUpdated.toIso8601String(),
      'status': status.index,
      'lastActivity': lastActivity?.toIso8601String(),
    };
  }

  // 从JSON反序列化
  factory ExamState.fromJson(Map<String, dynamic> json) {
    // 处理旧数据中的 _last_activity 字段
    DateTime? lastActivity;
    final answers = json['answers'] is Map ? Map<String, dynamic>.from(json['answers']) : <String, dynamic>{};

    // 如果新字段存在，使用新字段
    if (json['lastActivity'] != null) {
      lastActivity = DateTime.parse(json['lastActivity']);
    }
    // 如果旧字段存在，迁移到新字段并从answers中删除
    else if (answers.containsKey('_last_activity')) {
      final lastActivityValue = answers['_last_activity'];
      if (lastActivityValue is int) {
        lastActivity = DateTime.fromMillisecondsSinceEpoch(lastActivityValue);
      }
      answers.remove('_last_activity'); // 从answers中删除，避免影响答题数统计
    }

    return ExamState(
      examId: json['examId'],
      userId: json['userId'],
      examTitle: json['examTitle'] ?? '未知考试', // 兼容旧数据
      answers: answers,
      remainingSeconds: json['remainingSeconds'] ?? 0,
      lastUpdated: json['lastUpdated'] != null
          ? DateTime.parse(json['lastUpdated'])
          : DateTime.now(),
      status: ExamStatus.values[json['status'] ?? 0],
      lastActivity: lastActivity,
    );
  }
}

class ExamResult {
  final String id;
  final String examId;
  final String userId;
  final Map<String, dynamic> answers; // 用户答案，key为题目ID，value为用户答案
  final Map<String, int> scores; // 每道题的得分，key为题目ID，value为得分
  final Map<String, List<String>> answerImages; // 用户答题照片，key为题目ID，value为图片路径列表
  final int totalScore; // 总得分
  final int objectiveScore; // 客观题总得分
  final int subjectiveScore; // 主观题总得分
  final DateTime? submittedAt; // 提交时间
  final bool isGraded; // 是否已经完全评分（含主观题）
  final String? avatarPath; // 新增：考试头像路径
  final int? usedTimeInMinutes; // 答题用时（分钟）

  ExamResult({
    required this.id,
    required this.examId,
    required this.userId,
    Map<String, dynamic>? answers,
    Map<String, int>? scores,
    Map<String, List<String>>? answerImages,
    int? totalScore,
    int? objectiveScore,
    int? subjectiveScore,
    DateTime? submittedAt,
    bool? isGraded,
    this.avatarPath,
    this.usedTimeInMinutes,
  }) :
    answers = answers ?? {},
    scores = scores ?? {},
    answerImages = answerImages ?? {},
    totalScore = totalScore ?? 0,
    objectiveScore = objectiveScore ?? 0,
    subjectiveScore = subjectiveScore ?? 0,
    submittedAt = submittedAt,
    isGraded = isGraded ?? false;

  // 工厂构造函数，创建一个新的考试结果
  factory ExamResult.createNew({
    required String id,
    required String examId,
    required String userId,
    String? avatarPath,
  }) {
    return ExamResult(
      id: id,
      examId: examId,
      userId: userId,
      avatarPath: avatarPath,
    );
  }
  
  // 兼容旧代码的 create 方法
  factory ExamResult.create({
    required String examId,
    required String userId,
    required Map<String, dynamic> answers,
    String? avatarPath,
    int? usedTimeInMinutes,
  }) {
    return ExamResult(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      examId: examId,
      userId: userId,
      answers: answers,
      submittedAt: DateTime.now(),
      avatarPath: avatarPath,
      usedTimeInMinutes: usedTimeInMinutes,
    );
  }

  // 更新客观题得分
  ExamResult updateObjectiveScores(Map<String, int> newScores, int totalObjective) {
    Map<String, int> updatedScores = Map.from(scores)..addAll(newScores);

    return ExamResult(
      id: id,
      examId: examId,
      userId: userId,
      answers: answers,
      scores: updatedScores,
      answerImages: answerImages,
      totalScore: totalObjective + subjectiveScore,
      objectiveScore: totalObjective,
      subjectiveScore: subjectiveScore,
      submittedAt: submittedAt,
      isGraded: isGraded,
      avatarPath: avatarPath,
      usedTimeInMinutes: usedTimeInMinutes,
    );
  }

  // 更新主观题得分
  ExamResult updateSubjectiveScores(Map<String, int> newScores, int totalSubjective) {
    Map<String, int> updatedScores = Map.from(scores)..addAll(newScores);

    return ExamResult(
      id: id,
      examId: examId,
      userId: userId,
      answers: answers,
      scores: updatedScores,
      answerImages: answerImages,
      totalScore: objectiveScore + totalSubjective,
      objectiveScore: objectiveScore,
      subjectiveScore: totalSubjective,
      submittedAt: submittedAt,
      isGraded: true, // 主观题已评分，考试完全评分
      avatarPath: avatarPath,
      usedTimeInMinutes: usedTimeInMinutes,
    );
  }

  // 添加答题照片
  ExamResult addAnswerImage(String questionId, String imagePath) {
    final updatedAnswerImages = Map<String, List<String>>.from(answerImages);

    // 如果该题目已有图片列表，则添加到列表中，否则创建新列表
    if (updatedAnswerImages.containsKey(questionId)) {
      updatedAnswerImages[questionId]!.add(imagePath);
    } else {
      updatedAnswerImages[questionId] = [imagePath];
    }

    return ExamResult(
      id: id,
      examId: examId,
      userId: userId,
      answers: answers,
      scores: scores,
      answerImages: updatedAnswerImages,
      totalScore: totalScore,
      objectiveScore: objectiveScore,
      subjectiveScore: subjectiveScore,
      submittedAt: submittedAt,
      isGraded: isGraded,
      avatarPath: avatarPath,
      usedTimeInMinutes: usedTimeInMinutes,
    );
  }

  // 删除答题照片
  ExamResult removeAnswerImage(String questionId, String imagePath) {
    final updatedAnswerImages = Map<String, List<String>>.from(answerImages);

    if (updatedAnswerImages.containsKey(questionId)) {
      updatedAnswerImages[questionId]!.remove(imagePath);

      // 如果列表为空，删除该键
      if (updatedAnswerImages[questionId]!.isEmpty) {
        updatedAnswerImages.remove(questionId);
      }
    }

    return ExamResult(
      id: id,
      examId: examId,
      userId: userId,
      answers: answers,
      scores: scores,
      answerImages: updatedAnswerImages,
      totalScore: totalScore,
      objectiveScore: objectiveScore,
      subjectiveScore: subjectiveScore,
      submittedAt: submittedAt,
      isGraded: isGraded,
      avatarPath: avatarPath,
      usedTimeInMinutes: usedTimeInMinutes,
    );
  }

  // 序列化方法
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'examId': examId,
      'userId': userId,
      'answers': answers,
      'scores': scores,
      'answerImages': answerImages,
      'totalScore': totalScore,
      'objectiveScore': objectiveScore,
      'subjectiveScore': subjectiveScore,
      'submittedAt': submittedAt?.toIso8601String(),
      'isGraded': isGraded,
      'avatarPath': avatarPath,
      'usedTimeInMinutes': usedTimeInMinutes,
    };
  }

  // 从JSON反序列化
  factory ExamResult.fromJson(Map<String, dynamic> json) {
    // 处理成绩映射，确保正确解析
    Map<String, int> parsedScores = {};
    if (json['scores'] is Map) {
      (json['scores'] as Map).forEach((key, value) {
        parsedScores[key.toString()] = int.tryParse(value.toString()) ?? 0;
      });
    }

    // 处理图片路径映射
    Map<String, List<String>> parsedAnswerImages = {};
    if (json['answerImages'] is Map) {
      (json['answerImages'] as Map).forEach((key, value) {
        if (value is List) {
          parsedAnswerImages[key.toString()] = List<String>.from(value);
        }
      });
    }

    return ExamResult(
      id: json['id'] ?? DateTime.now().millisecondsSinceEpoch.toString(),
      examId: json['examId'] ?? '',
      userId: json['userId'] ?? '',
      answers: json['answers'] is Map ? json['answers'] : {},
      scores: parsedScores,
      answerImages: parsedAnswerImages,
      totalScore: json['totalScore'] ?? 0,
      objectiveScore: json['objectiveScore'] ?? 0,
      subjectiveScore: json['subjectiveScore'] ?? 0,
      submittedAt: json['submittedAt'] != null ? DateTime.parse(json['submittedAt']) : null,
      isGraded: json['isGraded'] ?? false,
      avatarPath: json['avatarPath'],
      usedTimeInMinutes: json['usedTimeInMinutes'],
    );
  }
}